<template>
  <view class="company-container">
    <view class="form-content">
      <view class="form-title flex align-item-center">
        <view class="line"></view>新能源信息
        <view class="ml-20" v-if="meterForm.updateType"
          ><up-tag size="mini" :text="meterForm.updateType" plain plainFill>
          </up-tag
        ></view>
      </view>
      <view
        class="checkStatus"
        v-if="meterForm.checkStatus"
		@click="openCheckStatus"
        :class="{ warnColor: meterForm.checkStatus == '审核不通过' }"
      >
        {{ meterForm.checkStatus }}
      </view>
      <up-form
        labelPosition="left"
        :model="meterForm"
        ref="meterFormRef"
        labelWidth="120px"
      >
        <up-form-item label="设备名称" prop="name" borderBottom required>
          <up-input
            v-model="meterForm.name"
            placeholder="请输入设备名称"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item label="设备编码" prop="energyCode" borderBottom>
          <up-input
            v-model="meterForm.energyCode"
            placeholder="请输入设备编码"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item
          label="热源利用类型"
          prop="useType"
          borderBottom
          @click="formItemClick('useType')"
        >
          <up-input
            v-model="meterForm.useType"
            placeholder="请选择热源利用类型"
            disabled
            disabled-color="#ffffff"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-down"></up-icon>
          </template>
        </up-form-item>
        <up-picker
          :show="useTypeShow"
          :defaultIndex="useTypeIdx"
          :columns="[useTypeArr]"
          @confirm="useTypeConfirm"
          @cancel="useTypeShow = false"
        ></up-picker>
        <up-form-item label="设备品牌" prop="brand" borderBottom>
          <up-input
            v-model="meterForm.brand"
            placeholder="请输入设备品牌"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item label="设备型号" prop="modelNumber" borderBottom>
          <up-input
            v-model="meterForm.modelNumber"
            placeholder="请输入设备型号"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item label="设备名义制热功率" prop="heatingPower" borderBottom>
          <up-input
            type="digit"
            v-model="meterForm.heatingPower"
            placeholder="请输入名义制热功率"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item label="制冷剂类型" prop="refrigerantType" borderBottom>
          <up-input
            v-model="meterForm.refrigerantType"
            placeholder="请输入制冷剂类型"
            border="none"
          ></up-input>
        </up-form-item>
        <up-form-item label="充填量(kg)" prop="fillingAmount" borderBottom>
          <up-input
            type="digit"
            v-model="meterForm.fillingAmount"
            placeholder="请输入充填量"
            border="none"
          ></up-input>
        </up-form-item>

        <up-form-item label="铭牌照片" prop="deviceNameplateImage" borderBottom>
          <up-upload
            :fileList="meterForm.deviceNameplateImage"
            @afterRead="afterRead"
            @delete="deletePic"
            :previewFullImage="true"
            name="1"
            multiple
            :maxCount="3"
          ></up-upload>
        </up-form-item>
        <up-form-item label="设备照片" prop="deviceImage">
          <up-upload
            :fileList="meterForm.deviceImage"
            @afterRead="afterReadDevice"
            @delete="deleteDevicePic"
            :previewFullImage="true"
            name="1"
            multiple
            :maxCount="3"
          ></up-upload>
        </up-form-item>
      </up-form>
      <view class="bottom-btn">
        <up-button
          type="primary"
          color="#4e6ef2"
          shape="circle"
          @click="handleSubmit"
          >保存</up-button
        >
      </view>
    </view>
  </view>
</template>

<script>
import {
  getDictList,
  addSaveNewEnergy,
  getNewEnergyInfo,
  uploadImg,
  deleteImg,
} from '../../api/company';
export default {
  data() {
    return {
      dialogType: 'add',
      meterForm: {
        companyId: '',
        stationId: '',
        energyCode: '', //设备编号
        name: '', //设备名称
        useType: '', //热源利用类型
        brand: '', //品牌
        modelNumber: '', //型号
        heatingPower: '', //名义制热功率（MW）
        refrigerantType: '', //制冷剂类型
        fillingAmount: '', //充填量
        deviceNameplateImage: [], //铭牌照片
        deviceImage: [], //设备照片
        sort: 10,
      },
      useTypeShow: false,
      useTypeArr: [],
      useTypeIdx: [],
      rules: {
        name: [
          {
            required: true,
            message: '请填写设备名称',
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  onLoad(options) {
    this.initData(options);
  },
  mounted() {
    this.$refs.meterFormRef.setRules(this.rules);
  },
  methods: {
    async initData(options) {
      const { type, energyInfo } = options;
      this.dialogType = type;
      uni.setNavigationBarTitle({
        title: type == 'add' ? '添加新能源' : '新能源详情',
      });

      let energyObj = JSON.parse(decodeURIComponent(energyInfo));

      this.meterForm.companyId = energyObj.companyId;
      this.meterForm.stationId = energyObj.stationId;

      if (this.dialogType !== 'add') {
        const info = await getNewEnergyInfo(energyObj.id, { checkTag: 1 });
        const { deviceNameplateImage = [], deviceImage = [] } = info;
        this.meterForm = info;
        this.meterForm.deviceNameplateImage =
          deviceNameplateImage === null ? [] : deviceNameplateImage;
        this.meterForm.deviceImage = deviceImage === null ? [] : deviceImage;
      }
    },
	/**点击审核状态**/
	openCheckStatus(){
		const title=this.meterForm.checkOpinion||''
		if(title){
			uni.showModal({
				title:'审核意见',
				content:title
			})
		}
		
	},
    /**点击选项下拉**/
    async formItemClick(name) {
      if (name == 'useType') {
        const res = await getDictList('1865031771868000011');
        this.useTypeArr = res || [];
        if (this.meterForm.useType) {
          const idx = this.useTypeArr.findIndex(
            (item) => item == this.meterForm.useType
          );
          this.useTypeIdx = [idx];
        }
        this.useTypeShow = true;
      }
    },
    useTypeConfirm(e) {
      this.meterForm.useType = e.value[0];
      //   this.useTypeIdx = [e.indexs];
      this.useTypeShow = false;
    },
    /**上传图片**/
    async afterRead(event) {
      let lists = [].concat(event.file);

      let fileListLen = this.meterForm.deviceNameplateImage.length;
      lists.forEach((item) => {
        this.meterForm.deviceNameplateImage.push({
          url: item.url,
          size: item.size,
          status: 'uploading',
          message: '上传中',
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await uploadImg(lists[i].url, {
          stationId: this.meterForm.stationId,
        });
        let item = this.meterForm.deviceNameplateImage[fileListLen];
        this.meterForm.deviceNameplateImage.splice(
          fileListLen,
          1,
          Object.assign(
            {
              url: item.url,
              size: item.size,
            },
            {
              status: 'success',
              message: '',
              ...result,
            }
          )
        );
        fileListLen++;
      }
    },
    /**删除图片**/
    async deletePic(event) {
      const { index, file } = event;
      const res = await deleteImg({
        filePath: file.url,
      });
      uni.showToast({
        title: '删除照片成功！',
      });
      this.meterForm.deviceNameplateImage.splice(index, 1);
    },
    async afterReadDevice(event) {
      const fileList = [].concat(event.file);
      let fileImgLen = this.meterForm.deviceImage.length;
      fileList.forEach((item) => {
        this.meterForm.deviceImage.push({
          url: item.url,
          size: item.size,
          status: 'uploading',
          message: '上传中',
        });
      });

      for (let i = 0; i < fileList.length; i++) {
        const result = await uploadImg(fileList[i].url, {
          stationId: this.meterForm.stationId,
        });
        let item = this.meterForm.deviceImage[fileImgLen];
        this.meterForm.deviceImage.splice(
          fileImgLen,
          1,
          Object.assign(
            {
              url: item.url,
              size: item.size,
            },
            {
              status: 'success',
              message: '',
              ...result,
            }
          )
        );
        fileImgLen++;
      }
    },
    /**删除设备照片**/
    async deleteDevicePic(event) {
      const { index, file } = event;
      const res = await deleteImg({
        filePath: file.url,
      });
      uni.showToast({
        title: '删除照片成功！',
      });
      this.meterForm.deviceImage.splice(index, 1);
    },
    /**保存**/
    handleSubmit() {
      this.$refs.meterFormRef
        .validate()
        .then((valid) => {
          if (valid) {
            const params = this.meterForm;
            addSaveNewEnergy(params).then((res) => {
              uni.$u.toast(this.dialogType == 'add' ? '添加成功' : '保存成功');
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index',
                });
              }, 1000);
            });
          } else {
            uni.$u.toast('校验失败');
          }
        })
        .catch(() => {
          // 处理验证错误
          uni.$u.toast('校验失败');
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.company-container {
  width: 100%;
  min-height: 100vh;
  padding: 30rpx 20rpx 200rpx 20rpx;
  box-sizing: border-box;
  position: relative;
  background: #f8f8f8;
}

.form-content {
  padding: 20rpx 20rpx;
  width: 100%;
  box-sizing: border-box;
  background: #fff;
  border-radius: 12rpx;
  position: relative;
  .form-title {
    font-size: 34rpx;
    font-weight: bold;
    text-indent: 10rpx;
    margin-bottom: 20rpx;
    .line {
      width: 5px;
      height: 15px;
      border-radius: 10px;
      display: inline-block;
      margin-right: 20rpx;
      vertical-align: -2rpx;
      background-color: #0e8fe5;
    }
  }
  .checkStatus {
    position: absolute;
    right: 0;
    top: 0;
    padding: 12rpx 20rpx;
    background-color: #f60;
    font-size: 25rpx;
    color: #fff;
    font-weight: bold;
    border-radius: 4rpx 12rpx 4rpx 12rpx;
    &.warnColor {
      background-color: #f56c6c;
    }
  }
}

.bottom-btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  padding: 40rpx 30rpx;
  left: 0;
  box-sizing: border-box;
  background: #fff;
  border-top: 1px solid #f4f4f4;
  z-index: 100;
}
</style>
